//
//  UIColor+Extension.swift
//  LSTools
//
//  Created by zrf on 2021/6/30.
//

import Foundation

extension UIColor{
    /**
     @brief 根据rgb值生成UIColor
     @author rf/2021-06-08
     */
    public static func rgb(r: Int, g: Int, b: Int, a: CGFloat = 1) -> UIColor{
        return UIColor(red: r.cgf/255.0, green: g.cgf/255.0, blue: b.cgf/255.0, alpha: a)
    }
    /**
     @brief 根据16进制整型值生成UIColor
     @author rf/2021-06-08
     */
    public static func hexColor(_ hex: Int, a: CGFloat = 1) -> UIColor {
        let red = (hex >> 16) & 0xFF
        let green = (hex >> 8) & 0xFF
        let blue = hex & 0xFF
        return rgb(r: red, g: green, b: blue, a: a)
    }
    public static func hexColor(_ hexString: String, a: CGFloat = 1) -> UIColor {
        var string = ""
        let lowercaseHexString = hexString.lowercased()
        if lowercaseHexString.hasPrefix("0x") {
            string = lowercaseHexString.replacingOccurrences(of: "0x", with: "")
        } else if hexString.hasPrefix("#") {
            string = hexString.replacingOccurrences(of: "#", with: "")
        } else {
            string = hexString
        }

        if string.count == 3 { // convert hex to 6 digit format if in short format
            var str = ""
            string.forEach { str.append(String(repeating: String($0), count: 2)) }
            string = str
        }
        let hexValue = Int(string, radix: 16) ?? 0
        return hexColor(hexValue, a: a)
    }
    /**
     @brief 将view.backgroundcolor转为image
     */
    public func toImage() -> UIImage {
        let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        context!.setFillColor(self.cgColor)
        context!.fill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
    /**
     @brief 更新UIColor的alpha值
     @param ap alpha值 0到1
     */
    public func alpha(_ ap: CGFloat) -> UIColor {
        self.withAlphaComponent(ap)
    }
    /**
     @brief 主色，可重载更改
     */
    open class var main: UIColor {
        get{
            return Self.hexColor("#417FF9")
        }
    }
}
